package com.thread.xxstudy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class FutureTaskTest {

    //int类型未防止多线程加volatile是没用的  因为++s并不是原子性操作   使用原子操作类可以
      int s = 0;
    AtomicInteger ss = new AtomicInteger(0);

    class WaitTime implements Callable {

        @Override
        public Object call() throws Exception {
            Thread.sleep(2000);
           String c = "call--" + (ss.incrementAndGet());
          //  String c = "call--" + (++s);
            System.out.println(c);
            return c;
        }
    }

  /*  public static void main(String[] args) {
        new FutureTaskTest().callRun();
    }*/


    void callRun() {
        WaitTime waitTime = new WaitTime();

        List<java.util.concurrent.FutureTask<String>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            java.util.concurrent.FutureTask<String> s = new java.util.concurrent.FutureTask<String>(waitTime);
            list.add(s);
            new Thread(s).start();

        }


        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        list.forEach(new Consumer<java.util.concurrent.FutureTask<String>>() {
            @Override
            public void accept(java.util.concurrent.FutureTask<String> waitTime) {
                try {
                    if (waitTime.isDone()) {
                        String waitTime1 = waitTime.get();
                        System.out.println(waitTime1);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

        });
    }
}

